#!/bin/bash -x

test_pod_dir="$HOME/workspace/pod-workload"

registry_ip_addr=""
registry_port=31313
registry=""

pod_yaml="${test_pod_dir}/simple-pod.yaml"
pod_name="busybox"
pod_container_image_basename="busybox:latest"
pod_runtimeclass="kata-qemu-csv"
pod_container_image_uri=""

usage () {
  set +x
  echo -e "\033[31m
Usage: $0 <-h|<-i <registry-ip-addr>> [-p <registry-port>] [-r <kata-coco-runtimeclass>]>

       -h,--help         Display this help message
       -i,--ip           The ip address of the local registry
       -p,--port         The port number of the local registry
       -r,--runtimeclass Specify the runtimeclass
                         Valid value are shown as following:
                             kata-qemu-coco-dev
                             kata-qemu-csv
                             kata-qemu-csv2
                             kata-qemu-csv3
                         Default is kata-qemu-csv
\033[0m"
  set -x
}

params=$(getopt -o hi:p:r: --long help,ip:,port:,runtimeclass: -- "$@")
if [ $? -ne 0 ]; then
  echo "[Error] cannot parse parameters"
  exit 1
fi

eval set -- "$params"

while true; do
  case "$1" in
  -h|--help)
    usage
    exit 0
    ;;
  -i|--ip)
    registry_ip_addr="$2"
    shift 2
    ;;
  -p|--port)
    registry_port="$2"
    shift 2
    ;;
  -r|--runtimeclass)
    pod_runtimeclass="$2"
    shift 2
    ;;
  --)
    shift
    break
    ;;
  *)
    usage
    exit 1
    ;;
  esac
done

if [ "X${registry_ip_addr}" = "X" ]; then
  usage
  exit 1
fi

registry="${registry_ip_addr}:${registry_port}"
pod_container_image_uri="${registry}/${pod_container_image_basename}"

generate_pod_yaml () {
  echo "[Generate Pod yaml]"

  if [ ! -d $(dirname ${pod_yaml}) ]; then
    mkdir -p $(dirname ${pod_yaml})
  fi

  cat <<EOF | tee ${pod_yaml}
apiVersion: v1
kind: Pod
metadata:
  labels:
    run: simple-${pod_name}
  name: simple-${pod_name}
  annotations:
    io.containerd.cri.runtime-handler: ${pod_runtimeclass}
    io.katacontainers.config.hypervisor.kernel_params: ""
spec:
  containers:
  - image: ${pod_container_image_uri}
    name: ${pod_name}-c1
  dnsPolicy: ClusterFirst
  runtimeClassName: ${pod_runtimeclass}
EOF
}

generate_pod_yaml

run_pod () {
  echo "[Run Pod]"
  kubectl delete -f ${pod_yaml} || true
  kubectl apply -f ${pod_yaml}
}

run_pod
